﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace DevManager.Services;

public static class OrderRunService
{
    public static async Task<string> Run(string s)
    {
        var terminal = new Process();
        terminal.StartInfo.FileName = "cmd.exe";
        terminal.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        terminal.StartInfo.UseShellExecute = false;//是否使用操作系统shell启动
        terminal.StartInfo.CreateNoWindow = true;
        terminal.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
        terminal.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
        terminal.StartInfo.RedirectStandardError = true;//重定向标准错误输出
        terminal.Start();
        await terminal.StandardInput.WriteLineAsync(s);//指令
        terminal.StandardInput.Close();
        terminal.Dispose();
        return await terminal.StandardOutput.ReadToEndAsync();
    }

    public static async Task<string> Run(IEnumerable<string> strings,bool isCd = false)
    {
        using var terminal = new Process();
        terminal.StartInfo.FileName = "cmd.exe";
        terminal.StartInfo.UseShellExecute = false;//是否使用操作系统shell启动
        terminal.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息
        terminal.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息
        terminal.StartInfo.RedirectStandardError = true;//重定向标准错误输出
        var enumerable = strings as string[] ?? strings.ToArray();
        if(isCd)
            terminal.StartInfo.Arguments = enumerable.FirstOrDefault();
        terminal.Start();
        foreach (var value in enumerable)
            await terminal.StandardInput.WriteLineAsync(value);//指令
        
        terminal.StandardInput.Close();
        return await terminal.StandardOutput.ReadToEndAsync();
    }
}

public class CommandRunner
{
    private string ExecutablePath { get; }
    private string? WorkingDirectory { get; }

    public CommandRunner(string? executablePath, string? workingDirectory = null)
    {
        
        ExecutablePath = executablePath ?? throw new ArgumentNullException(nameof(executablePath));
        WorkingDirectory = workingDirectory ?? Path.GetDirectoryName(executablePath);
    }

    public string Run(string arguments)
    {
        var info = new ProcessStartInfo(ExecutablePath, arguments)
        {
            CreateNoWindow = true,
            RedirectStandardOutput = true,
            UseShellExecute = false,
            WorkingDirectory = WorkingDirectory,
        };
        var process = new Process
        {
            StartInfo = info
        };
        try
        {
            process.Start();
            return process.StandardOutput.ReadToEnd();
        }
        catch
        {
            return "Null";
        }
    }
}